package com.crscd.controller;

import com.alibaba.cloud.ai.dashscope.embedding.DashScopeEmbeddingOptions;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.NamedBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2025/10/6-12:18
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@RestController
@Slf4j
public class Embed2VectorController {
  @Resource private EmbeddingModel embeddingModel;
  @Resource private VectorStore vectorStore;

  @Value("${spring.ai.dashscope.embedding.options.model}")
  private String embeddingModelName;

  @GetMapping("/text2embed")
  public EmbeddingResponse text2Embed(String msg) {
    final EmbeddingResponse embeddingResponse =
        embeddingModel.call(
            new EmbeddingRequest(
                List.of(msg),
                DashScopeEmbeddingOptions.builder().withModel(embeddingModelName).build()));
    log.info(Arrays.toString(embeddingResponse.getResult().getOutput()));
    return embeddingResponse;
  }

  @GetMapping("/embed2vector/add")
  public void add() {
    List<Document> documents =
        List.of(
            new Document("i study llm"), new Document("i love java"), new Document("i use java 8"));
    vectorStore.add(documents);
  }

  @GetMapping("/embed2vector/get")
  public List<Document> getAll(@RequestParam(name = "msg") String msg) {
    SearchRequest searchRequest = SearchRequest.builder().query(msg).topK(2).build();
    final List<Document> documents = vectorStore.similaritySearch(searchRequest);
    System.out.println(documents);
    return documents;
  }
}
